package com.apec.delay.consumer;

import com.apec.delay.constants.DelayConstants;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@Component
public class DeadLetterQueueConsumer {

    @RabbitListener(queues = DelayConstants.DEAD_LETTER_QUEUEA_NAME)
    public void receiveA(Message message, Channel channel) throws IOException {
        String msg = new String(message.getBody());
        log.info("当前时间：{},死信队列A收到消息：{}", formatDate(new Date()), msg);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    @RabbitListener(queues = DelayConstants.DEAD_LETTER_QUEUEB_NAME)
    public void receiveB(Message message, Channel channel) throws IOException {
        String msg = new String(message.getBody());
        log.info("当前时间：{},死信队列B收到消息：{}", formatDate(new Date()), msg);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


    @RabbitListener(queues = DelayConstants.DELAYED_QUEUE_NAME)
    public void receiveD(Message message, Channel channel) throws IOException {
        String msg = new String(message.getBody());
        log.info("当前时间：{},延时队列收到消息：{}", formatDate(new Date()), msg);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    public static final String FORMAT_DATE_TIME = "yyyy-MM-dd HH:mm:ss";

    public static String formatDate(Date date) {
        String s = "";
        if (date != null) {
            SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_DATE_TIME);
            s = sdf.format(date);
        }
        return s;
    }
}